package top.jsjkxyjs.blackbox.ws;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import top.jsjkxyjs.blackbox.service.EventService;
import top.jsjkxyjs.blackbox.service.IotService;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;

@ServerEndpoint(value = "/Charts", configurator = MyEndpointConfigure.class)
@Component
public class UserIotDataEndpoint {
	public static EventService eventService;
	public static IotService iotService;
	private HttpSession httpSession;

	@OnOpen
	public void onOpen(Session session, EndpointConfig config) throws IOException, InterruptedException {
		httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
	}

	@OnMessage
	public void onMessage(Session session, int massage) throws IOException, InterruptedException {
		ObjectMapper mapper = new ObjectMapper();
		while (httpSession.getAttribute("user") != null) {
			Map fi = iotService.getUserIotDataLimit(massage, "Fi");
			session.getBasicRemote().sendText(mapper.writeValueAsString(fi));
			Thread.sleep(250);
			Map tem = iotService.getUserIotDataLimit(massage, "tem");
			mapper = new ObjectMapper();
			session.getBasicRemote().sendText(mapper.writeValueAsString(tem));
			Thread.sleep(250);
			Map hum = iotService.getUserIotDataLimit(massage, "hum");
			mapper = new ObjectMapper();
			session.getBasicRemote().sendText(mapper.writeValueAsString(hum));
			Thread.sleep(250);
			Map location = iotService.getUserIotDataLimit(massage, "location");
			session.getBasicRemote().sendText(mapper.writeValueAsString(location));
			Thread.sleep(250);

		}

	}

	@OnClose
	public void onClose() {

	}
}
